#!/bin/bash
##########################configuration##########################
operator_server_source_ip="172.16.1.119"
operator_server_source_user_name="yapai"
operator_server_source_password="ypkj$%^7"
operator_server_target_ip="172.16.1.119"
operator_server_target_user_name="postgres"
operator_server_target_password="postgres"
base_template_sql_folder="${HOME}/temp/yapai/system-init"
base_folder="${HOME}/temp/mysql"
trans_middle_database="test"
##########################configuration##########################
project_name=$1
table_names=`mysql -h${operator_server_source_ip} -u${operator_server_source_user_name} -p${operator_server_source_password} -e 'use '"${project_name}"';show tables' | sed -n '2,$p'`
remove_default_sql_template="ALTER TABLE {{project_name}}.{{table_name}} ALTER COLUMN {{field_name}} DROP DEFAULT;"
change_bool_2_int2_sql_template="ALTER TABLE {{project_name}}.{{table_name}} ALTER COLUMN {{field_name}} TYPE int USING {{field_name}}::int;"
add_default_sql_template="ALTER TABLE {{project_name}}.{{table_name}} ALTER COLUMN {{field_name}} SET DEFAULT 0;"
# ALTER TABLE nanshan.t_location ALTER COLUMN is_leaf DROP DEFAULT;
# ALTER TABLE nanshan.t_location ALTER COLUMN is_leaf TYPE int2 USING is_leaf::int2;
# ALTER TABLE nanshan.t_location ALTER COLUMN is_leaf SET DEFAULT 0;
whole_sql=""
for table_name in ${table_names[@]}
do
  tinyint_filed=`mysql -h${operator_server_source_ip} -u${operator_server_source_user_name} -p${operator_server_source_password} -e 'use '"${project_name}"';desc '"${table_name}"'' | grep 'tinyint(1)' | awk '{print $1}'`
  if [[ -z ${tinyint_filed} ]]
  then
    continue
  fi
  for field_name in ${tinyint_filed[@]}
  do
    real_sql=`echo ${remove_default_sql_template} | sed -n 's/{{project_name}}/'"${project_name}"'/g;p' | sed -n 's/{{table_name}}/'"${table_name}"'/g;p' | sed -n 's/{{field_name}}/'"${field_name}"'/g;p'`
    whole_sql=${whole_sql}${real_sql}
    real_sql=`echo ${change_bool_2_int2_sql_template} | sed -n 's/{{project_name}}/'"${project_name}"'/g;p' | sed -n 's/{{table_name}}/'"${table_name}"'/g;p' | sed -n 's/{{field_name}}/'"${field_name}"'/g;p'`
    whole_sql=${whole_sql}${real_sql}
    real_sql=`echo ${add_default_sql_template} | sed -n 's/{{project_name}}/'"${project_name}"'/g;p' | sed -n 's/{{table_name}}/'"${table_name}"'/g;p' | sed -n 's/{{field_name}}/'"${field_name}"'/g;p'`
    whole_sql=${whole_sql}${real_sql}
  done
done
if [[ ! -z ${whole_sql} ]]
then
  echo ${whole_sql}
  # psql -h ${operator_server_target_ip} -U${operator_server_target_user_name} -d${trans_middle_database} -c "${whole_sql}"
fi
